<template>
  <a-modal :title="title" :after-close="reset" @ok="submit">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ style: { width: '80px' } }">
      <a-form-item name="name" label="部门名称">
        <a-input v-model:value="form.name" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="上级部门" name="parentId">
        <a-tree-select v-model:value="form.parentId" placeholder="请选择" allow-clear show-search style="width: 100%"
          :tree-line="{ showLine: true }" tree-default-expand-all :tree-data="deptTree" tree-data-simple-mode
          tree-node-filter-name="title" @change="onSelectNodeChange" />
      </a-form-item>
      <a-form-item name="orderNum" label="排序号">
        <a-input-number v-model:value="form.orderNum" :min="0" :precision="0" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { getDeptTree } from '@/api/sys';
import { saveDept } from '@/api/dept';
import { Dept, type IFlatDept } from '@/types/dept';
import { validReg } from '@/utils/validate';

const props = withDefaults(defineProps<{
  data: Partial<Dept>
}>(), {
})
const title = computed(() => props.data.deptId ? '编辑' : '新增')
const { formRef, submit, close } = useDialog({ validCallback: save })

let form = $ref(new Dept())
watchEffect(() => {
  if (props.data.deptId) {
    nextTick(() => {
      form.setProps(props.data as Dept)
    })
  }
})

const rules = {
  name: [validReg('required', '请输入用户名')],
  parentId: [validReg('required', '请选择上级部门', 'change')],
}

onMounted(() => {
  getDeptData()
})
const emit = defineEmits(['change'])
function save() {
  saveDept(form).then(() => {
    AntMessage.success('保存成功')
    close()
    emit('change')
  })
}

let deptData = $ref<IFlatDept[]>([])
const deptTree = computed(() => {
  if (props.data.deptId) {
    return deptData.filter(dept => dept.pId !== props.data.deptId && dept.value !== props.data.deptId)
  }
  return deptData
})
function getDeptData() {
  getDeptTree().then((res) => {
    res.push({
      title: '一级部门',
      value: 0,
      id: 0
    })
    deptData = res
  })
}
function onSelectNodeChange(value: number, label: string[]) {
  if (value === 0) {
    return
  }
  form.parentName = label[0]
}

function reset() {
  form = new Dept()
}
</script>

<style lang="less"></style>